from django import forms
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.shortcuts import render
from django_user_agents.utils import get_user_agent
from django.http import JsonResponse

# Create your views here.
from polls.models import Question
from polls import models

import datetime
import copy

from polls.static_1 import *
import random

import inspect


def __Line__():
    stack_t = inspect.stack()
    ttt = inspect.getframeinfo(stack_t[1][0])
    return ttt.lineno


def __Func__():
    stack_t = inspect.stack()
    ttt = inspect.getframeinfo(stack_t[1][0])
    return ttt.function


def __File__():
    stack_t = inspect.stack()
    ttt = inspect.getframeinfo(stack_t[1][0])
    return ttt.filename


# 107 -- 查询历史的内容

# 展示当前时间 一般用作 调试使用 打印当前时间
def datetime_now():
    print("[",
          datetime.datetime.now().hour, ":",
          datetime.datetime.now().minute, ":",
          datetime.datetime.now().second, "]")


# 测试用已经被废弃了
def index(request):
    # url index  主页面  请求数据库内容 进行返回
    # 这个东西目前没用怎么弄  显示的内容是原生的内容 没用增加  前端的 图标
    # 这个东西  看网上的是  使用 遍历拿到东西  然后给前端的   我改一下  或者直接使用 json传值？？？ 算了先这个样子把
    latest_question_list = Question.objects.order_by('-pub_data')[:5]
    print("打印 latest_question_list 里面的东西 ", type(latest_question_list),
          latest_question_list)

    list_to_html = []
    for i in latest_question_list:
        list_to_html.append([
            i.id, i.question_text,
            i.pub_data.strftime('%Y-%m-%d %H:%M:%S')
            # i.pub_data.strftime('%Y-%m-%d %H:%M:%S.%f')  这个是显示毫秒内容的 部分
        ])

    context = {
        "list_to_html": list_to_html,
        "latest_question_list": latest_question_list,
    }
    datetime_now()
    return render(request, 'index.html', context)


# 获取最后一个用户的id
def get_last_user_id():
    latest_question_list = models.UserInfo.objects.all()
    del_to_html = {}
    # 看一下这个拿到的 数据是如何排列的
    list_to_html = []
    for i in latest_question_list:
        list_to_html.append(
            [i.id, i.name, i.password, i.age, i.account, i.create_time])
    return list_to_html[-1][0]


# from app01 import models


# 将操作历史记录插入到 his表里面去 其中函数额外增加 当前时间一列
def inst_his(id, key, trans="无"):
    models.His.objects.create(
        id_did=id,
        did_his_key=key,
        trance_text=trans,
        Time_sta=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))


def depart_list(request):
    """ 部门列表 """

    # 去数据库中获取所有的部门列表
    #  [对象,对象,对象]
    queryset = models.Department.objects.all()

    return render(request, 'depart_list.html', {'queryset': queryset})


def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request, 'depart_add.html')

    # 获取用户POST提交过来的数据（title输入为空）
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.create(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    # 获取ID http://127.0.0.1:8000/depart/delete/?nid=1
    nid = request.GET.get('nid')

    # 删除
    models.Department.objects.filter(id=nid).delete()

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == "GET":
        # 根据nid，获取他的数据 [obj,]
        row_object = models.Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html', {"row_object": row_object})

    # 获取用户提交的标题
    title = request.POST.get("title")

    # 根据ID找到数据库中的数据并进行更新
    # models.Department.objects.filter(id=nid).update(title=title,其他=123)
    models.Department.objects.filter(id=nid).update(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


# url user_liscontent_type = {str} 'text/plain't
def user_list(request):
    """ 用户管理 """
    # 获取所有用户列表 [obj,obj,obj]
    queryset = models.UserInfo.objects.all()
    inst_his(0, 102, trans="查看所有用户信息 列表")
    return render(request, 'user_list.html', {"queryset": queryset})


# url  http://127.0.0.1:8000/user/add/
# 获取网页传参   并解析放到数据库里面去 user_add.html --> user_list.html
def user_add(request):
    """ 添加用户（原始方式） """
    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    # 获取用户提交的数据  有报错这个里面返回 user_add.html页面
    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        age = request.POST.get('age')
        account = request.POST.get('ac')
        ctime = request.POST.get('ctime')
        # print("===========", ctime)
        gender = request.POST.get('gd')
        depart_id = request.POST.get('dp')

        # 拿到的这些数据 --  user  pwd  age  account  ctime  gender 1 depart_id 1
        #  （啥都不写是这个东i下）
        print("拿到的这些数据 -- ", "user", user, "pwd", pwd, "age", age, "account",
              account, "ctime", ctime, "gender", gender, "depart_id",
              depart_id)

        if (user):
            print("用户输入和user内容 不输入默认名字")
        else:
            print("用户没输入user内容 输入默认名字")
            user = fake_lis_2[random.randint(0, len(fake_lis_2))]

        if (pwd):
            pass
        else:
            pwd = random.randint(1000, 9999)

        if (age):
            pass
        else:
            age = random.randint(10, 90)

        if (account):
            pass
        else:
            account = (random.randint(10, 90)) * 1000

        if (ctime):
            pass
        else:
            ctime = "2023-08-13"

        # 插入的信息 这个东西 里面的具体内容
        # user, pwd, age, account, ctime, gender, depart_id = \
        # fake_lis_2[random.randint(0,len(fake_lis_2))], rand_int, rand_int1, 1000, "2023-08-13 20:40:07.000", 1, 1
        # 添加到数据库中
        try:
            models.UserInfo.objects.create(name=user,
                                           password=pwd,
                                           age=age,
                                           account=account,
                                           create_time=ctime,
                                           gender=gender,
                                           depart_id=depart_id)
        # 从这里在进入到 user_add.html里面去 这个会带进去一个 error_msg 用来表示错误
        except:
            context = {
                "error_msg": "1",
                'gender_choices': models.UserInfo.gender_choices,
                "depart_list": models.Department.objects.all()
            }
            return render(request, 'user_add.html', context)
    inst_his(get_last_user_id(), 101, trans="添加用户")
    return redirect("/user/list/")


# 删除用户  user/del  user_del.html
# 默认删除   工号最大的用户
def user_del(request):
    # 获取最后一个用户的工号  感觉这个真的不如 sql用着好用  就是单纯的写sql舒服
    latest_question_list = models.UserInfo.objects.all()
    del_to_html = {}
    # 看一下这个拿到的 数据是如何排列的
    list_to_html = []
    for i in latest_question_list:
        list_to_html.append(
            [i.id, i.name, i.password, i.age, i.account, i.create_time])
    del_ = models.UserInfo.objects.get(id=list_to_html[-1][0])
    # 这个就可以拿到 操作的内容了
    new_del = copy.deepcopy(del_)
    context = {
        "pass": "pass",
        "del_to_html": new_del,
    }
    # 先关闭这个删除的操作
    if (1):
        del_.delete()

    print("最后一个员工为 -- ", list_to_html[-1][0])
    print("传入 html内容为 -- ", list_to_html[-1])
    print("传入 html内容为 -- ", del_)
    inst_his(list_to_html[-1][0], 103, trans="删除最后一个用户")
    return render(request, 'user_del.html', context)


# 根据指定id删除 用户 这个可以了
def user_del_by_id(request, del_id):
    printf("拿到的id", del_id)
    # 拿到要删除的id了 执行进行删除的命令
    # 这个就可以拿到 操作的内容了

    del_ = models.UserInfo.objects.get(id=del_id)

    new_del = copy.deepcopy(del_)
    context = {
        "pass": "pass",
        "del_to_html": new_del,
    }

    # 先关闭这个删除的操作
    if (1):
        del_.delete()
    inst_his(del_id, 104, trans="删除用户根据指定id")
    return render(request, 'user_del.html', context)


# 修改用户信息  修改最后一个信息
def user_change_by_id_last(request):
    # 给 模板部分传给一些东西 最上面显示  原本的内容下面 也是 原本的内容 但是可以进行修改和编辑的内容  那么要想弄这个里面的这些东西就需要我们 对这个进行修改了  就是  先把注册的里面的东西弄清楚  弄好
    if request.method == "GET":
        change_id = get_last_user_id()
        change_val = models.UserInfo.objects.get(id=change_id)
        printf("change_val--", change_id)
        printf(models.UserInfo.gender_choices, models.Department.objects.all())
        context = {
            "pass": "",
            "del_to_html": change_val,
            'gender_choices': models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }
        # return HttpResponse(f"<h1>函数user_change_by_id{change_id}</h1>")
        return render(request, 'user_change.html', context)
    # id是主键 根据这个修改其他的信息
    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        age = request.POST.get('age')
        account = request.POST.get('ac')
        ctime = request.POST.get('ctime')
        print("===========", ctime)
        gender = request.POST.get('gd')
        depart_id = request.POST.get('dp')

        print("change函数里面 -- ", "user", user, "pwd", pwd, "age", age,
              "account", account, "ctime", ctime, "gender", gender,
              "depart_id", depart_id)

        # 执行sql 使用sql进行操作

        change_id = get_last_user_id()
        try:
            models.UserInfo.objects.filter(id=change_id).update(
                name=user,
                password=pwd,
                age=age,
                account=account,
                create_time=ctime,
                gender=gender,
                depart_id=depart_id)
        except:
            change_id = get_last_user_id()
            change_val = models.UserInfo.objects.get(id=change_id)
            printf("change_val--", change_id)
            printf(models.UserInfo.gender_choices,
                   models.Department.objects.all())
            # context=
            context = {
                "error": "用户输入信息错误请重新输入",
                "del_to_html": change_val,
                'gender_choices': models.UserInfo.gender_choices,
                "depart_list": models.Department.objects.all()
            }
            return render(request, 'user_change.html', context)

    change_val = models.UserInfo.objects.get(id=change_id)
    context = {
        "success": "1",
        "del_to_html": change_val,
        'gender_choices': models.UserInfo.gender_choices,
        "depart_list": models.Department.objects.all()
    }
    inst_his(change_id, 105, trans="修改用户信息-最后一个用户")
    return render(request, 'user_change.html', context)


# 根据url传过来的 id参数对 信息进行修改
def user_change_by_id_temp(request, change_id_url):
    change_id = change_id_url
    if request.method == "GET":
        # change_id = get_last_user_id()

        change_val = models.UserInfo.objects.get(id=change_id)
        printf("change_val--", change_id)
        printf(models.UserInfo.gender_choices, models.Department.objects.all())
        context = {
            "pass": "pass",
            "del_to_html": change_val,
            'gender_choices': models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }

        # return HttpResponse(f"<h1>函数user_change_by_id{change_id}</h1>")
        return render(request, 'user_change.html', context)
    # id是主键 根据这个修改其他的信息
    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        age = request.POST.get('age')
        account = request.POST.get('ac')
        ctime = request.POST.get('ctime')
        print("===========", ctime)
        gender = request.POST.get('gd')
        depart_id = request.POST.get('dp')

        print("change函数里面 -- ", "user", user, "pwd", pwd, "age", age,
              "account", account, "ctime", ctime, "gender", gender,
              "depart_id", depart_id)

        try:
            models.UserInfo.objects.filter(id=change_id).update(
                name=user,
                password=pwd,
                age=age,
                account=account,
                create_time=ctime,
                gender=gender,
                depart_id=depart_id)
        except:
            change_val = models.UserInfo.objects.get(id=change_id)
            context = {
                "error": "用户输入信息错误请重新输入",
                "del_to_html": change_val,
                'gender_choices': models.UserInfo.gender_choices,
                "depart_list": models.Department.objects.all()
            }
            return render(request, 'user_change.html', context)
    # 都正确返回修改信息正确的 内容
    change_val = models.UserInfo.objects.get(id=change_id)
    context = {
        "success": "1",
        "del_to_html": change_val,
        'gender_choices': models.UserInfo.gender_choices,
        "depart_list": models.Department.objects.all()
    }
    inst_his(change_id, 106, trans="修改用户信息-根据用户id")
    return render(request, 'user_change.html', context)


# 这个逻辑和 查询  list一样
def get_his(request):
    # 获取所有用户列表 [obj,obj,obj]
    queryset = models.His.objects.all()
    inst_his(0, 107, trans="查看所有历史记录")
    return render(request, 'user_his.html', {"queryset": queryset})


def get_his_back(request):
    queryset = models.His.objects.order_by("-Time_sta")
    inst_his(0, 108, trans="查看所有历史记录-时间倒叙")
    return render(request, 'user_his.html', {"queryset": queryset})


# 根据指定 操作人的id聚合查询
def get_his_key(request, key_his_id):
    queryset = models.His.objects.filter(id_did=key_his_id)
    inst_his(0, 109, trans="查询历史-指定id")
    print("get_his_key", key_his_id, queryset)
    return render(request, 'user_his.html', {"queryset": queryset})


# 根据指定 操作人的id聚合查询
def get_his_key_type(request, key_type):
    queryset = models.His.objects.filter(did_his_key=key_type)
    inst_his(0, 109, trans="查询历史-指定id")
    return render(request, 'user_his.html', {"queryset": queryset})


# 获取 user_agent
# python req的请求是这个东西   测试爬虫或者其他相关的内容  view标记
# request  会附带 好多东西
def useragent(request):
    if request.method == "GET":
        user_agent = get_user_agent(request)
        print("自己写的这个东西--user_agent", user_agent)
        # print("para--",request.query_params)
        for k, v in request.GET.items():
            print("获取的url传参--", k, v)
        print("cookies--",request.COOKIES)
        print("path_info--",request.path_info)
        data = {'name': 'John', 'age': 30, 'city': 'New York'}

        print(request.method)  # 请求方式
        print(request.body)  # 请求体
        print(request.META)  # 请求头
        print(request.GET)  # url里面的参数都在GET url？a=1&b=2
        print(request.POST)  # k-v,k1-v1
        print(request.FILES)  # 文件


        # 返回包含JSON数据的响应
        return JsonResponse(data)
    if request.method == "POST":
        pass
